﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using System.Data;
using System.Data.SqlClient;
using VAdvantage.Utility;
using System.Collections;
using System.Text;
using System.ComponentModel;

namespace VAdvantage.Controls
{
    public partial class VSortTab : UserControl
    {

        private int winNumber;

        private string tableName = null;
        private string columnSortName = null;
        private string columnYesNoName = null;
        private string keyColumnName = null;
        private string identifierColumnName = null;
        private bool identifierTranslated = false;

        private string parentColumnName = null;

        private Apps.APanel aPanel = null;

        private Logging.VLogger log = Logging.VLogger.GetVLogger(typeof(VSortTab).FullName);

        public VSortTab()
        {
            InitializeComponent();
        }




        public VSortTab(int windowNo, int AD_Table_ID, int AD_ColumnSortOrder_ID, int AD_ColumnSortYesNo_ID)
        {
            log.Config("SortOrder=" + AD_ColumnSortOrder_ID + ", SortYesNo=" + AD_ColumnSortYesNo_ID);
            winNumber = windowNo;

            try
            {
                InitializeComponent();

                Init();

                DynInit(AD_Table_ID, AD_ColumnSortOrder_ID, AD_ColumnSortYesNo_ID);
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
                //Common.ErrorLog.FillErrorLog("VSortTab Constructor", "", e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
            }
        }

        private void Init()
        {

            this.lblNo.Content = Msg.GetMsg(VAdvantage.Utility.Envs.GetCtx(), "No", true);
            this.lblYes.Content = Msg.GetMsg(VAdvantage.Utility.Envs.GetCtx(), "Yes", true);
            lstNo.DisplayMemberPath = "Key";
            lstYes.DisplayMemberPath = "Key";
            lstYes.SelectionMode = SelectionMode.Extended;
            lstNo.SelectionMode = SelectionMode.Extended;

        }


        private void DynInit(int AD_Table_ID, int AD_ColumnSortOrder_ID, int AD_ColumnSortYesNo_ID)
        {

            bool trl = !VAdvantage.Utility.Envs.IsBaseLanguage(VAdvantage.Utility.Envs.GetCtx(), "");



            String sql = "SELECT t.TableName, c.AD_Column_ID, c.ColumnName, e.Name,"	//	1..4
                + "c.IsParent, c.IsKey, c.IsIdentifier, c.IsTranslated "				//	4..8
                + "FROM AD_Table t, AD_Column c, AD_Element e "
                + "WHERE t.AD_Table_ID="+AD_Table_ID						//	#1
                + " AND t.AD_Table_ID=c.AD_Table_ID"
                + " AND (c.AD_Column_ID="+AD_ColumnSortOrder_ID+" OR AD_Column_ID="+AD_ColumnSortYesNo_ID 	//	#2..3
                + " OR c.IsParent='Y' OR c.IsKey='Y' OR c.IsIdentifier='Y')"
                + " AND c.AD_Element_ID=e.AD_Element_ID";
             //  GlobalVariable.IsBaseLanguage();
            if (trl)
                sql = "SELECT t.TableName, c.AD_Column_ID, c.ColumnName, et.Name,"	//	1..4
                    + "c.IsParent, c.IsKey, c.IsIdentifier, c.IsTranslated "		//	4..8
                    + "FROM AD_Table t, AD_Column c, AD_Element_Trl et "
                    + "WHERE t.AD_Table_ID="+AD_Table_ID						//	#1
                    + " AND t.AD_Table_ID=c.AD_Table_ID"
                    + " AND (c.AD_Column_ID="+ AD_ColumnSortOrder_ID +" OR AD_Column_ID="+AD_ColumnSortYesNo_ID	//	#2..3
                    + "	OR c.IsParent='Y' OR c.IsKey='Y' OR c.IsIdentifier='Y')"
                    + " AND c.AD_Element_ID=et.AD_Element_ID"
                    + " AND et.AD_Language='" + Envs.GetAD_Language(VAdvantage.Utility.Envs.GetCtx()) + "'";						//	#4


            var client = AEnv.GetDataServiceDBClient();

            client.GetDataXMLCompleted +=(sc,ec)=>
                {
                    if(ec.Error != null)
                    {
                    }
                    else if (ec.ServiceError != null)
                    {
                        log.Severe(ec.ServiceError.Message);
                    }

                    else
                    {
                        IDataReader dr = null;
                        try
                        {
                            dr = new DataReader();
                            dr.SetData(ec.Result);

                            while (dr.Read())
                            {
                                tableName = dr.GetString(0);
                                //	Sort Column
                                if (AD_ColumnSortOrder_ID == Util.GetValueOfInt(dr[1]))
                                {
                                    log.Fine("Sort=" + dr.GetString(0) + "." + dr.GetString(2));
                                    columnSortName = dr.GetString(2);
                                    lblYes.Content = dr.GetString(3);
                                }
                                //	Optional YesNo
                                else if (AD_ColumnSortYesNo_ID == Util.GetValueOfInt(dr[1]))
                                {
                                    log.Fine("YesNo=" + dr.GetString(0) + "." + dr.GetString(2));
                                    columnYesNoName = dr.GetString(2);
                                }
                                //	Parent2
                                else if (dr.GetString(4).Equals("Y"))
                                {
                                    log.Fine("Parent=" + dr.GetString(0) + "." + dr.GetString(2));
                                    parentColumnName = dr.GetString(2);
                                }
                                //	KeyColumn
                                else if (dr.GetString(5).Equals("Y"))
                                {
                                    log.Fine("Key=" + dr.GetString(0) + "." + dr.GetString(2));
                                    keyColumnName = dr.GetString(2);
                                }
                                //	Identifier
                                else if (dr.GetString(6).Equals("Y"))
                                {
                                    log.Fine("Identifier=" + dr.GetString(0) + "." + dr.GetString(2));
                                    identifierColumnName = dr.GetString(2);
                                    if (trl)
                                        identifierTranslated = "Y".Equals(dr.GetString(7));
                                }
                                else
                                {
                                    log.Fine("??NotUsed??=" + dr.GetString(0) + "." + dr.GetString(2));
                                }
                            }
                            dr.Close();

                        }
                        catch (Exception e)
                        {
                            if (dr != null)
                            {
                                dr.Close();
                            }
                            log.Log(Logging.Level.SEVERE, sql.ToString(), e);
                            //Common.ErrorLog.FillErrorLog("VTabPane", sql, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
                        }

                        lblNo.Content = Msg.GetMsg(VAdvantage.Utility.Envs.GetCtx(), "Available", true);
                        log.Info(columnSortName);

                    }

                };

            client.GetDataXMLAsync(sql,null,null);
            client.CloseAsync();
        }




        /// <summary>
        /// Save Field Sequence
        /// </summary>
        public void SaveData()
        {
            if (!aPanel.IsSaveEnabled())
                return;
            log.Info("");
            StringBuilder sql = null;


            this.Cursor = Cursors.Wait;
            List<String> queries = new List<String>();
            //	noList - Set SortColumn to null and optional YesNo Column to 'N'
            for (int i = 0; i < lstNo.Items.Count; i++)
            {
                KeyValuePair<string, int> pp = (KeyValuePair<string, int>)lstNo.Items[i];
                sql = new StringBuilder();
                sql.Append("UPDATE ").Append(tableName)
                    .Append(" SET ").Append(columnSortName).Append("=0");
                if (columnYesNoName != null)
                    sql.Append(",").Append(columnYesNoName).Append("='N'");
                sql.Append(" WHERE ").Append(keyColumnName).Append("=").Append(pp.Value);

                queries.Add(sql.ToString());
            }
            //if (SqlExec.ExecuteQuery.ExecuteNonQuery(sql.ToString()) != 1)
            //{
            //    //Common.ErrorLog.FillErrorLog("VSortTab", "", "NoModel - Not updated: " + keyColumnName + "=" + pp.Value.ToString(), VAdvantage.Framework.Message.MessageType.ERROR);
            //    log.Log(Logging.Level.SEVERE, "NoModel - Not updated: " + keyColumnName + "=" + pp.Value.ToString());
            //}
            //}

            //	yesList - Set SortColumn to value and optional YesNo Column to 'Y'
            for (int i = 0; i < lstYes.Items.Count; i++)
            {
                KeyValuePair<string, int> pp = (KeyValuePair<string, int>)lstYes.Items[i];
                sql = new StringBuilder();
                sql.Append("UPDATE ").Append(tableName)
                    .Append(" SET ").Append(columnSortName).Append("=").Append(i + 1).Append("0");	//	10 steps
                if (columnYesNoName != null)
                    sql.Append(",").Append(columnYesNoName).Append("='Y'");
                sql.Append(" WHERE ").Append(keyColumnName).Append("=").Append(pp.Value);

                queries.Add(sql.ToString());
            }
            //if (SqlExec.ExecuteQuery.ExecuteNonQuery(sql.ToString()) != 1)
            //{
            //    Common.ErrorLog.FillErrorLog("VSortTab", "", "NoModel - Not updated: " + keyColumnName + "=" + pp.Value.ToString(), VAdvantage.Framework.Message.MessageType.ERROR);
            //    log.Log(Logging.Level.SEVERE, "YesModel - Not updated: " + keyColumnName + "=" + pp.Value.ToString());
            //}
            //}

            var client = AEnv.GetDataServiceBasic2Client();
            client.ExecuteMultipleQueriesCompleted += (sc, ec) =>
                {
                    if (ec.Error != null)
                    {
                    }
                    else if (ec.ServiceError != null)
                    {
                        Classes.ShowMessage.Error("Error?", true, ec.ServiceError.ToString());
                    }
                    else
                    {
                        List<String> ret = ec.Result;

                        foreach (String str in ret)
                        {
                            log.Log(Level.SEVERE, "Model - Not Updated:=" + str); 
                        }
                    }
                    this.Cursor = Cursors.Arrow;
                    if(aPanel != null)
                    {
                    aPanel.SetBusy(false, false);
                    }
                };

            client.ExecuteMultipleQueriesAsync(queries,null);
            client.CloseAsync();
        }

        internal void UnRegisterVForm()
        {
            SaveData();
            aPanel = null;
        }

        internal void RegisterVForm(Apps.APanel pnl)
        {
            aPanel = pnl;
        }

       
           /// <summary>
        /// Load data(fields) in Lists
        /// </summary>
        public void LoadData()
        {
            this.Cursor = Cursors.Wait;
            lstNo.Items.Clear();
            lstYes.Items.Clear();

            StringBuilder sql = new StringBuilder("");
            
            sql.Append("SELECT t.").Append(keyColumnName)				//	1
               .Append(identifierTranslated ? ",tt." : ",t.")
                   .Append(identifierColumnName)						//	2
               .Append(",t.").Append(columnSortName);				//	3
            if (columnYesNoName != null)
                sql.Append(",t.").Append(columnYesNoName);			//	4
            //	Tables
            sql.Append(" FROM ").Append(tableName).Append(" t");
            if (identifierTranslated)
                sql.Append(", ").Append(tableName).Append("_Trl tt");
            //	Where
            sql.Append(" WHERE t.").Append(parentColumnName).Append("=@ID");
            if (identifierTranslated)
                sql.Append(" AND t.").Append(keyColumnName).Append("=tt.").Append(keyColumnName)
                    .Append(" AND tt.AD_Language='" + Envs.GetAD_Language(VAdvantage.Utility.Envs.GetCtx()) + "'");
            //	Order
            sql.Append(" ORDER BY ");
            if (columnYesNoName != null)
                sql.Append("4 DESC,");		//	t.IsDisplayed DESC
            sql.Append("3,2");				//	t.SeqNo, tt.Name 
            int ID = VAdvantage.Utility.Envs.GetCtx().GetContextAsInt(winNumber, parentColumnName);
            log.Config(sql.ToString() + " - ID=" + ID);

            BackgroundWorker bgw = new BackgroundWorker();

            IDataReader dr = null;

            bgw.DoWork += (sd, ed) =>
                {
                    SqlParameter[] param = new SqlParameter[1];
                    param[0] = new SqlParameter("@ID", ID);
                    dr = DataBase.DB.ExecuteReader(sql.ToString(), param);
                };

            bgw.RunWorkerCompleted += (sc, ec) =>
                {
                    try
                    {
                        while (dr.Read())
                        {
                            int key = Util.GetValueOfInt(dr[0]);
                            String name = dr.GetString(1);
                            int seq = Util.GetValueOfInt(dr[2]);
                            bool isYes = seq != 0;
                            if (columnYesNoName != null)
                                isYes = dr.GetString(3).Equals("Y");
                            //
                            KeyValuePair<string, int> pp = new KeyValuePair<string, int>(name, key);
                            if (isYes)
                                lstYes.Items.Add(pp);
                            else
                                lstNo.Items.Add(pp);
                        }
                        dr.Close();
                    }
                    catch (Exception e)
                    {
                        // if (!dr.IsClosed)
                        dr.Close();
                        log.Log(Level.SEVERE, sql.ToString(), e);
                        //Common.ErrorLog.FillErrorLog("SortTab Load()", sql.ToString(), e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
                    }
                    aPanel.SetSaveButton(false);
                    this.Cursor = Cursors.Arrow;
                };

            bgw.RunWorkerAsync();

            //	SELECT t.AD_Field_ID,t.Name,t.SeqNo,t.IsDisplayed FROM AD_Field t WHERE t.AD_Tab_ID=? ORDER BY 4 DESC,3,2
            //	SELECT t.AD_PrintFormatItem_ID,t.Name,t.SeqNo,t.IsPrinted FROM AD_PrintFormatItem t WHERE t.AD_PrintFormat_ID=? ORDER BY 4 DESC,3,2
            //	SELECT t.AD_PrintFormatItem_ID,t.Name,t.SortNo,t.IsOrderBy FROM AD_PrintFormatItem t WHERE t.AD_PrintFormat_ID=? ORDER BY 4 DESC,3,2
            //	Columns
        }
        

        private void Dispose()
        {
            aPanel = null;
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {

            Button btn = (Button)sender;
            bool change = false;

            if (btn.Name == "btnRight")
            {

                for (int i = 0; i < lstNo.SelectedItems.Count; i++)
                {
                    lstYes.Items.Add(lstNo.SelectedItems[i]);
                    lstYes.SelectedItem = lstNo.SelectedItems[i];
                    //lstNo.Items.Remove(lstNo.SelectedItems[i]);
                    lstNo.Items.Remove(lstNo.SelectedItems[i]);
                    i--;
                    change = true;
                }
            }
            else if (btn.Name == "btnLeft")
            {
                //lstNo.Items.AddRange(lstYes.SelectedItems);
                lstNo.SelectedIndex = -1;
                for (int i = 0; i < lstYes.SelectedItems.Count; i++)
                {
                    lstNo.Items.Add(lstYes.SelectedItems[i]);
                    lstNo.SelectedItem = lstYes.SelectedItems[i];
                    lstYes.Items.Remove(lstYes.SelectedItems[i]);
                    i--;
                    change = true;
                }
            }
            else
            {
                IList selObjects = lstYes.SelectedItems;
                if (selObjects == null)
                {
                    return;
                }
                int length = selObjects.Count;
                if (length == 0)
                    return;
                Object selObject = selObjects[0];
                if (selObject == null)
                    return;

                //IList indices = ;
                int index = lstYes.SelectedIndex;
                if (index == -1)
                    return;
                selObject = lstYes.Items[index];
                if (selObject == null)
                    return;

                if (btn.Name == "btnUp")
                {
                    if (index == 0)
                        return;

                    //Object newObject = lstYes.Items[index - 1];
                    //lstYes.Items.Insert( index,newObject);
                    lstYes.Items.RemoveAt(index);
                    lstYes.Items.Insert(index - 1, selObject);
                    lstYes.SelectedIndex = index - 1;
                    change = true;

                }
                else if (btn.Name == "btnDown")
                {
                    if (index >= lstYes.Items.Count-1)
                        return;
                    //Object newObject = lstYes.Items[index];
                    
                    //lstYes.Items.Insert( index,newObject);

                    lstYes.Items.RemoveAt(index);
                    lstYes.Items.Insert(index+1 , selObject);
                    lstYes.SelectedIndex = index+1 ;
                    change = true;
                }
            }
            if (change && aPanel != null)
            {
                aPanel.SetSaveButton(true);
            }
        }
    }
}
